package _05_二叉树;

import java.util.LinkedList;
import java.util.Queue;

public class _226_翻转二叉树 {

    // 思路，遍历二叉树，交换左右节点，即可
    public TreeNode invertTree(TreeNode root) {
        inorderTraversalAndInvert(root);
        return root;
    }

    // 先序遍历
    public void preorderTraversalAndInvert(TreeNode root) {
        if (root == null) return;
        // 交换左右节点
        TreeNode node = root.left;
        root.left = root.right;
        root.right = node;
        preorderTraversalAndInvert(root.left);
        preorderTraversalAndInvert(root.right);
    }

    // 中序遍历
    public void inorderTraversalAndInvert(TreeNode root) {
        if (root == null) return;

        inorderTraversalAndInvert(root.left);

        TreeNode node = root.left;
        root.left = root.right;
        root.right = node;

        inorderTraversalAndInvert(root.left);
    }

    // 后续遍历
    public void postOrderTraversalAndInvert(TreeNode root) {
        if (root == null) return;

        postOrderTraversalAndInvert(root.left);
        postOrderTraversalAndInvert(root.right);

        TreeNode node = root.left;
        root.left = root.right;
        root.right = node;
    }

    // 层序遍历
    public void levelOrderTraversalAndInvert(TreeNode root) {
        if (root == null) return;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();

            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;

            if (node.left != null) {
                queue.offer(node.left);
            }

            if (node.right != null) {
                queue.offer(node.right);
            }
        }
    }

}
